# coding:utf-8
from typing import Optional

from fastapi import APIRouter, Query, Path
from tortoise.expressions import Q

from app.admin.schemas.system import PostBase, PostUpdate
from app.admin.service.system.post import SystemPostService
from app.core.response import SuccessExtra, Success, Fail


router = APIRouter()


@router.get("/post/list", summary="岗位列表")
async def page_list(
        page: int = Query(1, description="页码"),
        limit: int = Query(10, description="每页数量"),
        name: str = Query(None, description="用户名称，用于搜索"),
        status: Optional[str] = Query(None, description="用户状态"),
):
    # 查询条件
    query = Q()
    if name:
        query &= Q(name__contains=name)
    if status and int(status) in [0, 1, 2]:
        query &= Q(status=status)
    model_service = SystemPostService()
    total, lists = await model_service.page_list(query, page, limit)
    data = [await obj.to_dict(m2m=True) for obj in lists]
    return SuccessExtra(data=data, total=total, page=page, limit=limit)


@router.get("/post/{item_id}", summary="查看岗位")
async def get_detail(item_id: int = Path(..., description="岗位ID"), ):
    model_service = SystemPostService()
    item_obj = await model_service.get_id(item_id)
    if not item_obj:
        return Fail(msg="岗位不存在")
    item_dict = await item_obj.to_dict(exclude_fields=["password"])
    return Success(data=item_dict)


@router.post("/post/create", summary="创建岗位")
async def create(data_in: PostBase):
    model_service = SystemPostService()
    # 查询条件
    query = Q()
    query &= Q(name=data_in.name) | Q(code=data_in.code)
    item = await model_service.find(query)
    if item:
        return Fail(msg="岗位名称已存在")
    new_item = await model_service.create(obj_in=data_in)
    if not new_item:
        return Fail(msg="创建岗位失败")
    return Success(msg="操作成功")


@router.post("/post/update", summary="更新岗位")
async def update(data_in: PostUpdate):
    model_service = SystemPostService()
    item = await model_service.update(obj_in=data_in)
    return Success(msg="操作成功")


@router.delete("/post/delete/{item_id}", summary="删除岗位")
async def delete(item_id: int = Path(..., description="岗位ID")):
    model_service = SystemPostService()
    await model_service.remove(item_id)
    return Success(msg="操作成功")
